<template>
  <div class="mainarea font-deep-def" style="font-size: 1.4rem">
      <div class="container">
          <h1 class="center mt-3 expin-title" style="color: black">
              <span style="color: rgb(230, 60, 60);">{{ SpeciesName }}</span> 层流火焰速度数据
          </h1>
          <b-row class="my-1">
              <!-- <b-col md="7" sm="12"  xs="12"> -->
              <b-col cols="12">
                  <b-row class="my-1 fireprop-firstline-adjust">
                      <b-col lg="2" md="12" class="my-1">
                          <h5 class="my-2">数据来源:</h5>
                      </b-col>
                      <b-col lg="10" md="12" class="my-1">
                          <b-nav-item-dropdown :text="reflist[selected].text" class="source_selector"> 
                              <b-dropdown-item @mousemove="dataDetails($event, item.detail)" @mouseleave="clearDataDetails()" @mousedown="copy($event,item.detail)" @contextmenu.prevent="" v-for="item in reflist" :key="item.value" @click="selected = item.value" >{{item.text}}+{{reflist}}</b-dropdown-item>
                          </b-nav-item-dropdown>
                      </b-col>
                  </b-row>
                  <b-row class="my-1 fireprop-lastline-adjust">
                      <b-col class="my-1" sm="3">
                          <h5 class="my-2">压力(<span>atm</span>):</h5>
                      </b-col>
                      <b-col class="my-1" sm="3">
                          <b-form-select  v-model="pressure" :options="Pressures"  :disabled="false && iisChartShow"/>
                      </b-col>
                      <b-col class="my-1" sm="3">
                          <h5 class="my-2">温度(K):</h5>
                      </b-col>
                      <b-col class="my-1" sm="3">
                          <b-form-select v-model="temprature" :options="filterdTemps" :disabled="false && iisChartShow" />
                      </b-col>
                      <b-col class="my-1" sm="12" style="flex: 0.3">
                          <h5 class="my-2">当量比可选范围:</h5>
                      </b-col>
                      <b-col class="my-1" sm="12" style="flex: 0.2">
                          <input class="form-control" v-model.lazy="ratioMin" :disabled="false && iisChartShow" />
                      </b-col>
                      <span class="my-1" style="text-align: center;">——</span>
                      <b-col class="my-1" sm="12" style="flex: 0.2">
                          <input class="form-control" v-model.lazy="ratioMax" :disabled="false && iisChartShow"/>
                      </b-col> 
                      <b-col v-show="false" offset-md="4">
                          <div style="color:black" class="my-4 mx-5">(可选范围为：{{filterdRatios[0]}}-{{filterdRatios[1]}} )</div>
                      </b-col>
                      <b-button class="expin-btn-search my-1" style="flex: 0.2" size="lg" variant="primary"  @click="handleSubmit" v-if="true || !isChartShow">
                          <icon name="search" scale="1.4"></icon>
                      </b-button>
                  </b-row>
              <!-- {{delayPressures}}{{delayTempratures}}{{delayTime}} -->
              
                  <!-- <hr v-if="!isChartShow"/>
                  <p style="text-align:center"  class="my-5">
                      <b-button size="lg" variant="primary"  @click="handleSubmit" v-if="!isChartShow">
                          点击提交
                      </b-button>
                      <b-button size="lg" variant="primary"  @click="handleReset" v-if="isChartShow">
                          重新选择
                      </b-button>
                      <b-alert :show="alertShow" class="mx-3 my-5" variant="warning">无符合条件的记录，请检查工况条件</b-alert>
                  </p> -->
              </b-col>  
          </b-row>
          <b-row>
              <b-col  cols="12" class="mb-3" >
                  <!-- <div align="right"><b-button @click="resetZoom"  v-if="isChartShow" >曲线重置<icon name="undo" class="ml-1"></icon></b-button></div> -->
                  <b-row>
                      <Chart class="mb-1 mx-auto col-lg-8 col-md-10 col-sm-12" v-if="isChartShow" :height="500" :data="chartData" :options="chartOptions" ></Chart> 
                  </b-row>
              </b-col>
              <template v-if="isChartShow">
                  <b-col cols="12" class="mt-3">
                      <a @click="showTable" style="cursor: pointer; text-decoration:underline" class="my-3"><icon name="circle" class="mx-1 " ></icon> 查看原始数据：</a>
                      <label style="color:black" class="mx-3" @click="hideTable" v-show="isTableShow"><icon name="angle-double-up"></icon> 隐藏</label>
                      
                      <table  class="table mt-3" style="border-collapse: initial;border: rgb(175, 176, 207) solid 0px;" v-show="isTableShow">
                      <thead class="">
                          <tr>
                              <th >当量比 (fuel%:O<sub>2</sub>%:diluent%) </th>
                              <th >层流火焰速度（cm/s）</th>
                              <th >测量误差（cm/s）</th>
                              
                          </tr>
                      </thead>
                      <tbody class="">
                          <tr v-for="(speed,ind) in filterdFlameSpeeds" :key="ind" :style="'background-color: '+(ind%2?'rgb(248, 248, 248);':'white;')">
                              <td class="pl-3">
                                  <h6>{{filterdFlameRatios[ind]}} ({{filterdProptions[ind]}})</h6>
                              </td>
                              <td class="pl-3">
                                  <h6>{{speed}}</h6>
                              </td>
                              <td class="pl-3">
                                  <h6>{{filterdErrorScopes[ind]}}</h6>
                              </td>
                              
                          </tr>   
                      </tbody>
                  </table>

                  <div class="my-3"><icon name="circle" class="mx-1 " ></icon> 参考文献：<div style="color:black" class="mx-4 my-3"><icon name="square" class="mx-1 " ></icon> {{Source}}</div></div>
                      <!-- <div class="my-3"><icon name="circle" class="mx-1 " ></icon> 参考文献：<div style="color:black" class="mx-4 my-3"><icon name="square" class="mx-1 " ></icon> {{Source}}</div></div> -->
                      
                  </b-col>
              </template>
              <b-col>
                  
              </b-col>
              
          </b-row>
          <div class="floatDiv" :style="{display: isShow,left: floatLeft,top: floatTop, width: '500px'}">
              {{floatData}} <span :style="{whiteSpace: 'nowrap',color: copyFlag?'green':'red'}">{{copyFlag?'[复制成功]':'[点击右键复制]'}}</span>
          </div>
      </div>
  </div>
</template>
<script>
import Chart from '@/components/Chart.vue'
import { flameSpeedApi,supplyOverview } from '../api/overView/index'

export default {
  components:{
      Chart
  },
  name:'FireProp',
  data () {
      return {
          floatData: "",
          floatLeft: "0",
          floatTop: "0",
          isShow: 'none',
          copyFlag: false,
          entries:'',
          SpeciesName:'',
          SpeciesNameEn:'',
          ratioMin:'',
          ratioMax:'',
          Source:'',
          filterdFlameSpeeds:'',
          filterdErrorScopes:'',
          filterdFlameRatios:'',
          filterdProptions:'',
          alertShow:false,
          ratio:'',
          ratios:[],
          reflist:[],
          selected: 0,
          ratioScopes:'',
          pressure:'',
          Pressures:[],
          Tempratures:'',
          temprature:'',
          isTableShow:false,
          isChartShow:false,
          chartOptions: {
              plugins: {
                  zoom: {
                      pan: {
                          enabled: false,
                          mode: 'x,y',
                          speed: 10,
                          threshold: 10
                      },
                      zoom: {
                          enabled: false,
                          mode: 'x,y'
                      }
                  },
                  chartJsPluginErrorBars: {
                      width: '8%',
                      color: '#007bff'
                  }
              },
                  
              scales: {
                  yAxes: [{
                      scaleLabel: {
                          display: true,
                          labelString: '层流火焰速度（cm/s）',
                          fontStyle: 'bold',
                          fontSize: 15,
                          
                      },
                      type: 'linear',
                      ticks: {
                          beginAtZero: false,
                          fontStyle: 'bold',
                          fontSize: 13
                      },
                  }],
                  xAxes: [{
                      display: true,
                      scaleLabel: {
                          display: true,
                          labelString: '当量比',
                          fontStyle: 'bold',
                          fontSize: 15
                      },
                      ticks: {
                          fontStyle: 'bold',
                          fontSize: 13
                      },
                      type: 'linear',
                      position: 'bottom',
                  }]
              },
              tooltips: {
                  intersect: true, // default: true. if true, the tooltip mode applies only when the mouse position intersects with an element. If false, the mode will be applied at all times.
                  callbacks: {
                      label: function(tooltipItem, data) {
                          // console.log(tooltipItem)
                          // console.log(data)
                          // var label = tooltipItem.yLabel + ' (' +data.labels[tooltipItem.index]+') ';
                          var label = data.datasets[tooltipItem.datasetIndex].label || '';
                          if (label) {
                              label += ': ';
                          }
                          label += tooltipItem.yLabel + ' (phi: ' +data.labels[tooltipItem.index]+') ';
                          return label;
                  }
                  }
              },
              legend: {
                  display: false
              },
              responsive: true,
              maintainAspectRatio: false,
              title: {
        display: true,
                  text: '层流火焰速度-当量比图',
                  fontSize: 25
      },

          },
      }
  },
  watch:{
      '$route'(to,from) {
          this.$router.go(0)
          console.log('name'+this.$route.query['Name'])
          if(this.$route.query['Name']){
              this.fetchData(this.$route.query['Name'] )
          }
      },
      pressure() {
          this.isChartShow = false;
      },
      temprature() {
          this.isChartShow = false;
      },
      selected(){
          // if (this.selected){
          this.isChartShow = false;
          this.selcss = []
          this.selcss[this.selected] = 'table-success'
          this.Source = this.entries[this.selected].Source
          this.Pressures = this.entries[this.selected].Pressures
          this.Tempratures = this.entries[this.selected].Tempratures
          this.ratioScopes = this.entries[this.selected].Ratios
          this.flamedatas = this.entries[this.selected].flamedatas
          this.pressure = this.Pressures[0]
          this.temprature = this.Tempratures[0][0]
          // }
          
      },
      floatData(val, oldVal) {
          if(val != oldVal)
              this.copyFlag = false;
      }
  },
  computed: {
      //根据指定压力进一步确定温度
      filterdTemps(){
          let tempratures = []
          this.Pressures.forEach((press,ind)=>{
              if(this.pressure==press){
                  tempratures = this.Tempratures[ind]
              }
          })
          return tempratures
      },
      filterdRatios(){
          this.sRatio = []
          this.sFlameSpeed = []
          this.sErrorScope = []
          this.sProptions = []
          let ratios = ''
          this.Pressures.forEach((press,ind)=>{
              if(this.pressure==press){
                  this.filterdTemps.forEach((temp,ind2)=>{
                      if(this.temprature == temp){
                          ratios =  this.ratioScopes[ind][ind2]
                          this.flamedatas[ind][ind2].forEach(data=>{
                              // let ens = [];
                              let name = data.substr(0, data.lastIndexOf("%")+1)
                              data = data.substr(data.lastIndexOf("%")+1)
                              // ens.push(this.SpeciesNameEn);
                              let ens = data.split(/\s+|\t+|,+/)
                              ens[0] = name;
                              ens = ens.filter(item=>item!="");
                              console.log(ens);
                              this.sProptions.push(ens[0])
                              this.sRatio.push(ens[1])
                              this.sFlameSpeed.push(ens[2])
                              this.sErrorScope.push(ens[3])
                          })
                      }
                  })
              }
          })
          let arr = ratios.split('-');
          this.ratioMin = arr[0];
          this.ratioMax = arr[1];
          return arr;
      },
      chartData () {
          // console.log(this.filterdFlameSpeeds)
          let yDatas = []
          let errorbars = {}
          this.filterdFlameSpeeds.forEach((d,i)=>{
              let obj ={
                  x: parseFloat(this.filterdFlameRatios[i]).toFixed(2),
                  y: d
              }
              let plus_minus = {}
              let erros = []
              if(this.filterdErrorScopes[i] && this.filterdErrorScopes[i].indexOf('-')!=-1){
                  erros = this.filterdErrorScopes[i].split('-')
              } else if(/±/.test(this.filterdErrorScopes[i])) {
                  erros[0] = this.filterdErrorScopes[i].replace("±","");
                  erros[1] = this.filterdErrorScopes[i].replace("±","");
              } else {
                  erros[0] = 0
                  erros[1] = this.filterdErrorScopes[i]
              }
              plus_minus['plus'] = erros[1]
              plus_minus['minus'] = erros[1]
              errorbars[this.filterdProptions[i]] = plus_minus
              yDatas.push(obj)
          })
          let errFlag = Object.values(errorbars).some(a=>!(a.minus&&a.plus));
          console.log(errorbars, errFlag);
          let datasets = [!errFlag?{
              label: 'SL',
              data: yDatas,
              // lineTension: 0,
              backgroundColor: 'transparent',
              borderColor: 'transparent',
              borderWidth: 0,
              pointRadius:10,
              pointStyle:'rect',
              pointBackgroundColor: '#007bff',
              showLine: true,
              errorBars:errorbars
          }:{
              label: 'SL',
              data: yDatas,
              // lineTension: 0,
              backgroundColor: 'transparent',
              borderColor: 'transparent',
              borderWidth: 0,
              pointRadius:10,
              pointStyle:'rect',
              pointBackgroundColor: '#007bff',
              showLine: true
          }]
          // console.log(this.filterdProptions)
          return {labels:this.filterdProptions,datasets: datasets}
      }
      
  },
  mounted() {
    this.fetchData('n-Hexadecane')
    // console.log(flameSpeedApi,supplyOverview)
      // if(this.$route.query['Name']){
      //     this.fetchData(this.$route.query['Name'] )
      //     // this.$store.state.speciesNames.forEach(name =>{
      //     //     if (name.En == this.$route.query['Name']) {
      //     //         this.SpeciesName = name.Ch
      //     //     }
      //     // })
      // }else{
      //     // this.$router.push({path: '/notfound'})
      // }
  },
  methods:{
      dataDetails (e, data) {
      this.floatData = data;
      this.floatLeft = e.clientX + 10 + 'px'; // 减去外层div的left距离
      this.floatTop = e.clientY + 'px';
      this.isShow = 'inline-block';
      },
      clearDataDetails () {
      this.isShow = 'none';
      },
      copy(e, data){
      // console.log(e);
      if(e.which == 3){
          let text = document.createElement("input");
          text.style="opacity:0;position:fixed;";
          text.id="clipTempInput"
          text.value=data;
          document.body.appendChild(text);
          document.getElementById("clipTempInput").select();
          this.copyFlag = document.execCommand("copy");
          // console.log(this.copyFlag);
          document.body.removeChild(text);
          return false;
      }
      return true;
      },
      resetZoom(){
          this.filterData()
      },
      fetchRef(ref){
          this.modal_show = true
          this.refrence = ref
      },
      fetchData(name){
          // console.log('name'+name)
          let para = {}
          para['Name'] = name
          flameSpeedApi(name).then(
              res => {
                  if(res.data!='Failed'){
                      res.data.sort((a,b)=>{return b.Year!=0?b.Year-a.Year:-1});
                      this.entries = res.data
                      res.data.forEach((element,ind) => {
                          if (element.Source){
                              this.reflist.push({ value: ind, text: element.Source_Tip, detail: element.Source })
                          }else{
                              this.reflist.push({ value: ind, text:''})
                          }  
                      });
                          // this.selcss[0] = 'table-success'
                          this.SpeciesName =   this.entries[0].Name_CN
                          this.SpeciesNameEn =   this.entries[0].Name
                          this.Source = this.entries[0].Source
                          // console.log(this.entries[0])
                          this.Pressures = this.entries[0].Pressures
                          this.Tempratures = this.entries[0].Tempratures
                          this.ratioScopes = this.entries[0].Ratios
                          this.flamedatas = this.entries[0].flamedatas
                          this.pressure = this.entries[0].Pressures[0]
                          this.temprature = this.entries[0].Tempratures[0][0]
                  }else{
                      this.entries = []
                      this.$router.push({path: '/notfound'})
                  }
              },reason => {
                  console.log(reason)
                  this.$router.push({path: '/ccdata/exp_search',query: {flag:'false'}})
              }
          )
      },
      handleSubmit(){
          console.log(1111)
          this.handleReset()
          this.filterdFlameRatios = []
          this.filterdFlameSpeeds = []
          this.filterdErrorScopes = []
          this.filterdProptions = []
          this.filterData()
          this.fetchYvalue_Min_Max()
          console.log(this.filterdFlameRatios.length)
          if(this.filterdFlameRatios.length>0){
              this.alertShow = false
              this.isChartShow = true
          }
          else{
              this.alertShow = true
          }
      },
      handleReset(){
          this.isChartShow = false
          this.isTableShow = false
      },
      showTable(){
          this.isTableShow = true
      },
      hideTable(){
          this.isTableShow = false
      },
      filterData(){
          let p = []
          let r = []
          let fs = []
          let e = []
          console.log(this.sRatio);
          for (let i=0; i<this.sRatio.length;i++){
              if (this.ratioMin && this.ratioMax){
                  if (parseFloat(this.sRatio[i]) >= parseFloat(this.ratioMin) &&  parseFloat(this.sRatio[i]) <=parseFloat(this.ratioMax)){
                      r.push(this.sRatio[i])
                      fs.push(this.sFlameSpeed[i])
                      e.push(this.sErrorScope[i])
                      p.push(this.sProptions[i])
                  }
              }
          }
          // 为何直接修改delayTempratures等不行，chart还是用没筛选过的？
          this.filterdFlameRatios = r
          this.filterdFlameSpeeds = fs
          this.filterdErrorScopes = e
          this.filterdProptions = p
          
      },
      //保证errorBar显示在图中
      fetchYvalue_Min_Max(){
          // console.log("11112312312312",this.filterdFlameSpeeds);
          let min = parseInt(this.filterdFlameSpeeds[0]); 
          let max = parseInt(this.filterdFlameSpeeds[1]);
          let errorBar = 0
          this.filterdFlameSpeeds.forEach((speed,ind)=>{
              speed = parseInt(speed);
              if (speed < min){
                  min = speed
              }else if(speed > max){
                  max = speed
              }
              // console.log(this.filterdErrorScopes, ind);
              // bug 这里的逻辑有点没理清楚，感觉应该是有问题的
              if(this.filterdErrorScopes[ind] && this.filterdErrorScopes[ind].indexOf('-')!=-1){
                  errorBar = this.filterdErrorScopes[ind].split('-')[1]
              } else if(/±/.test(this.filterdErrorScopes[ind])) {
                  errorBar = parseFloat(this.filterdErrorScopes[ind].replace("±", ""));
                  console.log(errorBar);
              } else{
                  errorBar = parseFloat(this.filterdErrorScopes[ind])         
              }
              
          })
          console.log(parseFloat(min) - isNaN(parseFloat(errorBar))?0:parseFloat(errorBar), parseFloat(max) + isNaN(parseFloat(errorBar))?0:parseFloat(errorBar))
          let min_v = parseFloat(min) - (isNaN(parseFloat(errorBar))?0:parseFloat(errorBar));
          let max_v = parseFloat(max) + (isNaN(parseFloat(errorBar))?0:parseFloat(errorBar));
          this.chartOptions.scales.yAxes[0].ticks.min = min_v%5==0?((min_v-5)/5).toFixed(0)*5:Math.floor(min_v/5)*5;
          this.chartOptions.scales.yAxes[0].ticks.max = max_v%5==0?((max_v+5)/5).toFixed(0)*5:Math.ceil(max_v/5)*5;
          this.chartOptions.scales.xAxes[0].ticks.min = this.ratioMin*1-0.1;
          this.chartOptions.scales.xAxes[0].ticks.max = this.ratioMax*1+0.1;
      }
  }
}
</script>
<style scoped>
.bg-info {
  background-color: #377BB5 !important
}
.table {
border:1px solid black;
color: black;
background-color:white;
}
.table th {

color: black;
vertical-align: middle;
background-color: white;
font-weight:bolder
}
.table thead th {
border-bottom-width: 1px;
}
.font-deep-def h5 {
font-size: 1.4rem;
}
.font-deep-def >>> select, .font-deep-def >>> input {
font-size: 1.3rem;
}
</style>
<style>

@media screen and (min-width: 1350px) {
  .fireprop-firstline-adjust div:first-child {
      flex: 12%;
      max-width: 12%;
  }
  .fireprop-firstline-adjust div:nth-child(2) {
      flex: 88%;
      min-width: 88%;
  }
  .fireprop-lastline-adjust div {
      flex: 12%;
      min-width: 12%;
  }
  .fireprop-lastline-adjust div:nth-child(n+2) {
      flex: 10%;
      min-width: 10%;
      max-width: 10%;
  }
  .fireprop-lastline-adjust div:nth-child(3) {
      flex: 11%;
      min-width: 11%;
      max-width: 11%;
  }
  .fireprop-lastline-adjust div:nth-child(5) {
      flex: 18%;
      min-width: 18%;
  }
  .fireprop-lastline-adjust .expin-btn-search {
      flex: 12%;
      min-width: 12%;
  }
}

@media screen and (max-width: 1350px) and (min-width: 992px){
  .fireprop-lastline-adjust div {
      min-width: 25%;
  }
  .fireprop-lastline-adjust .expin-btn-search {
      min-width: calc(25% - 60px);
  }
}
@media screen and (max-width: 992px) and (min-width: 768px){
  .fireprop-lastline-adjust div:nth-child(5) {
      min-width: 34%
  }
  .fireprop-lastline-adjust div:nth-child(n+6) {
      min-width: 20%
  }
  .fireprop-lastline-adjust .expin-btn-search {
      margin-left: 35px;
      min-width: calc(26% - 95px);
  }
}

@media screen and (max-width: 768px){
  .fireprop-lastline-adjust div:nth-child(5) {
      min-width: 100%
  }
  .fireprop-lastline-adjust div:nth-child(n+6) {
      min-width: 33%
  }
  .fireprop-lastline-adjust span {
      min-width: 33%;
  }
  .fireprop-lastline-adjust .expin-btn-search {
      margin-left: 35%;
      min-width: 30%;
  }
}
h5 {
  font-weight: bold;
}
@media (max-width: 820px){
  .col-sm-3 {
      flex: 100%;
      max-width: 100%;
  }
}
</style>
